<?php

namespace App\Applet\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Match;
use App\Models\User;
use App\Models\MatchReport;
use Encore\Admin\Facades\Admin;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Auth\RegistersUsers;
use Tymon\JWTAuth\Facades\JWTAuth;
use Carbon\Carbon;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\DecryptException;

class UserController extends Controller
{


    protected $miniProgram;
    public function __construct ()
    {
        $this->miniProgram =  Factory::miniProgram(config('miniProgram.config'));
    }

    public function makeUser(Request $request)
    {
        if ($request->type == 'match_report') {
            $uids_report = MatchReport::where('match_id', $request->match_id)->pluck('user_id')->toArray();
            $uids = User::whereNotIn('id', $uids_report)->limit(10)->pluck('id')->toArray();
            foreach ($uids as $uid) {
                MatchReport::reportMatch($uid, $request->match_id);
            }
        } else if ($request->type == 'user') {
            $users = factory(User::class, 30)->make()->toArray();
            User::insert($users);
        }
        dd(1);
    }

    // 报名活动
    public function reportMatch(Request $request)
    {
        $user = $this->getAuthenticatedUser();
        if (!$user) {
            return $this->error('亲，请先登录');
        }
        if (MatchReport::reportMatch($user->id, $request->match_id)) {
            return $this->success('报名成功');
        }
        return $this->error('报名失败');
    }

    // 登陆
    public function login()
    {
    	// dd(1);
    	// $user = Admin::user();
        $user = User::first();
        // $token = auth()->login($user);
        $token = JWTAuth::fromuser($user);
    	dd($token);
    }

    // 获取用户信息
    public function getInfo()
    {
        $user = $this->getAuthenticatedUser();
        if (!$user) {
            return $this->error('亲，请先登录');
        }
        $int = $user->id % 100;
        $user->name = '羽毛球' . $int;
        $user->avatar = 'https://alicdn.joyballet.cn/avatar/default_avatar.png';
        $user->group = '新人';
        $user->score = '3.5';
        return $this->success(['user' => $user]);
    }

    public function openIdLogin(Request $request)
    {
        $data = $this->validate(
            $request,
            [
                'code'  => 'required',
            ],
            [
                'code.required'  => '请传code用于获取openId',
            ]
        );
        $data = $this->miniProgram->auth->session($data['code']);
        $open_id = $data['openid'];
        $user = User::where('open_id',$data['openid'])->first();
        if (!$user && isset($request->phone)) {
            $user = User::where('phone', $request->phone)->first();
        }
        if (!$user){
            return $this->error('用户不存在');
        }
        if (isset($data['errcode'])) {
            return $this->failed('10004');
        }
        $user->open_id = $open_id;
        $user->save();
        $token = JWTAuth::fromuser($user);
        return  $this->success(['token'=>$token,'userInfo'=>$user], '登录成功');

    }


    // 注册
    public function regist(Request $request)
    {
        $v = Validator::make($request->all(), [
            'phone' => 'required:number',
            'password' => 'required',
        ], [
            'phone.required' => '电话不能为空',
            'phone.number' => '电话格式不正确',
            'password.required' => '密码不能为空',
        ]);
        if ($v->fails()) {
            return $this->error($v->errors()->first());
        }
        $d = Carbon::now()->toDateString();
        $p = Hash::make($request->password);
        $user = User::where('phone', $request->phone)->first();
        if (!$user) {
            $user = new User();
            $user->phone = $request->phone;
            $user->join_time = $d;
            $user->prevtime = $d;
            $user->password = $p;
        } else {
            if (!Hash::check($request->password, $user->password)) {
                return $this->error('密码或手机号错误');
            }
        }
        $user->login_time = $d;
        $user->login_ip = $request->getClientIp();
        $user->save();
        $token = JWTAuth::fromuser($user);
        return $this->success([
            'user' => $user,
            'token' => $token,
        ], '登录成功');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator($request)
    {
        return $request->validate([
            // 'name' => ['required', 'string', 'max:255'],
            'phone' => ['required', 'string', 'max:255', 'unique:users'],
            'code' => ['required', 'string', 'max:255', 'unique:users'],
            // 'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'phone' => $data['phone'],
            'password' => Hash::make($data['password']),
            'prevtime' => date('Y-m-d H:i:s'),
            'login_time' => date('Y-m-d H:i:s'),
            'login_ip' => '127.0.0.1',
            'join_time' => date('Y-m-d H:i:s'),
        ]);
    }

    public function getPhone(Request $request)
    {
        $rules = [
            'code'=>'required',
            'iv' => 'required',
            'encryptedData' => 'required',
        ];

        $message = [
            'code'=>'code 不能为空',
            'iv.required' => 'iv不能为空',
            'encryptedData.required' => 'encryptedData 不能为空',
        ];
        $info = Validator::make($request->all(), $rules, $message);
        if ($info->fails()) {
            return Response::Json([
                'message'=>$info->errors()->first(),
                'code'=>10000,
                'date'=>[]
            ]);
        }
        $data = $this->miniProgram->auth->session($request->code);
        if (isset($data['errcode'])) {
            return $this->error($data);
        }
        $session_key = $data['session_key'];
        try {
            $decryptedData = $this->miniProgram->encryptor->decryptData($session_key, $request->iv, $request->encryptedData);
        } catch (DecryptException $exception) {
            return  $this->error($exception->getMessage());
        }
        return $this->success($decryptedData);
    }
}